package com.amway.qy.util.common;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amway.qy.push.message.PushBaseMessage;
import com.google.gson.Gson;

public class MessageUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(MessageUtils.class);
    
    
	public static String convertRespMessageToJson(PushBaseMessage message){
		return new Gson().toJson(message);
		
	}
	
	
	/**
	 * 计算采用utf-8 编码方式时字符串所占字节数
	 *
	 * @param content
	 * @return
	 */
	public static int getByteSize(String content) {
		int size = 0;
		if(content != null){
			try{
				size = content.getBytes("utf-8").length;
			}catch (UnsupportedEncodingException e) {
				logger.error("", e);
			}
		}
		return size;
	}
	
	/**
	 * 解析微信发来的请求（XML）
	 * 
	 * @param inputstream --ByteArrayInputStream
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String> parseXml(ByteArrayInputStream inputStream) throws Exception {
		// 将解析结果存储在HashMap中
		Map<String, String> map = new HashMap<String, String>();
		// 读取输入流
		SAXReader reader = new SAXReader();
		Document document = reader.read(inputStream);
		// 得到xml根元素
		Element root = document.getRootElement();
		// 得到根元素的所有子节点
		List<Element> elementList = root.elements();
		// 遍历所有子节点
		for (Element e : elementList)
			map.put(e.getName(), e.getText());
		return map;
	}
}
